<template>
  <el-card class="form-container" shadow="never">
    <el-steps :active="activeStep" finish-status="success" align-center>
      <el-step title="商品信息" />
      <el-step title="商品属性" />
    </el-steps>
    <spu-info v-show="showStatus[0]" v-model="spu" :is-edit="isEdit" @nextStep="handleNextStep" />
    <spu-attr v-show="showStatus[1]" v-model="spu" :is-edit="isEdit" @prevStep="handlePrevStep" @finishCommit="handleFinishStep" />
  </el-card>
</template>

<script>
import SpuApi from '@/api/goods/SpuApi'
import SpuInfo from './components/SpuInfo'
import SpuAttr from './components/SpuAttr'

const defaultSpu = {
  spuName: null,
  sn: null,
  title: null,
  brandId: null,
  brandName: null,
  categoryId: null,
  categoryName: null,
  price: null,
  wholesalePrice: null,
  stock: null,
  warningStock: null,
  stockStatus: null,
  salesStatus: null,
  deliveryType: null,
  specParamTemplateId: null,
  freightTemplateId: null,
  specs: null,
  params: null,
  image: null,
  images: null,
  model: null,
  introduction: null,
  detailHtml: null,
  detailMobileHtml: null,
  saleService: null,
  saleQty: null,
  commentQty: null,
  isMarketable: null,
  isEnableSpec: null,
  status: '0'
}
export default {
  name: 'SpuList',
  components: {
    SpuInfo,
    SpuAttr
  },
  data() {
    return {
      isEdit: false,
      activeStep: 0,
      spu: Object.assign({}, defaultSpu),
      showStatus: [true, false, false, false]
    }
  },
  created() {
    const id = this.$route.params.id
    if (id) {
      this.isEdit = true
      SpuApi.get(id).then(response => {
        this.spu = response.data
      })
    }
  },
  methods: {
    handleHideStepAll() {
      for (let i = 0; i < this.showStatus.length; i++) {
        this.showStatus[i] = false
      }
    },
    handlePrevStep() {
      if (this.activeStep > 0 && this.activeStep < this.showStatus.length) {
        this.activeStep--
        this.handleHideStepAll()
        this.showStatus[this.activeStep] = true
      }
    },
    handleNextStep() {
      if (this.activeStep < this.showStatus.length - 1) {
        this.activeStep++
        this.handleHideStepAll()
        this.showStatus[this.activeStep] = true
      }
    },
    handleFinishStep() {
      if (this.isEdit) {
        SpuApi.edit(this.spu).then(response => {
          this.$message.success('修改成功')
          this.$router.back() // 返回上一页
        })
      } else {
        SpuApi.add(this.spu).then(response => {
          this.$message.success('添加成功')
          // location.reload() // 刷新当前页面
          this.$router.back() // 返回上一页
        })
      }
    }
  }
}
</script>
<style>
.form-container {
  width: 825px;
  /*position: absolute;*/
  left: 0;
  right: 0;
  padding: 35px 35px 15px;
  margin: 20px auto;
}
</style>
